import json

class StudentsDB:
    #学生信息管理系统数据模型
    def __init__(self):
        self.students = []
        self._load_students_data()
    
    def insert(self,student):
        #将学生数据数据插入列表
        self.students.append(student)
    
    def all(self):
        #返回所有学生数据
        return self.students
    
    def delete_by_name(self,name):
        #根据姓名删除学生数据
        for student in self.students:
            if student['name'] == name:
                self.students.remove(student)
                return True
        else:
            return False
        
    def search_by_name(self,name):
        #根据姓名查询学生数据
        for student in self.students:
            if student['name'] == name:
                return student
        else:
            return None
        
    def update(self,stu):
        #更新学生数据
        for i,student in enumerate(self.students):
            if student['name'] == stu['name']:
                self.students[i] = stu
                return True

    def _load_students_data(self):
        #加载学生数据
        with open('students.json','r',encoding='utf-8') as f:
            students = json.load(f)
        for student in students:
            self.insert(student)
            print('%s\t%d\t%d\t%d\t%d' % (student['name'], student['math'], student['chinese'], student['english'], student['total']))

    def save_data(self):
        #保存数据
        with open('students.json','w',encoding='utf-8') as f:
            json.dump(self.students,f,ensure_ascii=False)
    

    
db = StudentsDB()